package com.newly.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class WrapperResponseGlobalFilter /*implements GlobalFilter, Ordered*/ {

   /* @Override
    public int getOrder() {
        // -1 is response write filter, must be called before that
        return -2;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                AtomicReference<String> bodyRef = new AtomicReference<>();
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;

                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffers);
                        byte[] content = new byte[join.readableByteCount()];
                        *//*DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffers);

                        byte[] content = new byte[join.readableByteCount()];

                        join.read(content);
                        // 释放掉内存
                        DataBufferUtils.release(join);
                        String resultBody = new String(content, Charset.forName("UTF-8"));

                        originalResponse.getHeaders().setContentLength(resultBody.getBytes().length);*//*
                        HttpStatus statusCode = originalResponse.getStatusCode();
                        if (statusCode.value() == CodeConstant.AUTH_ERR) {
                            String str = JSONUtil.toJsonStr(R.fail(CodeConstant.AUTH_ERR, "鉴权失败！"));
                            return bufferFactory.wrap(str.getBytes());
                        }
                        //log.error("gateway catch service exception error:"+ resultBody);

                        return bufferFactory.wrap(content);
                    }));

                }
                // if body is not a flux. never got there.
                return super.writeWith(body);
            }
        };
        // replace response with decorator
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }*/

}